<template>
  <div>
    <el-container>
      <el-main>
        <div>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-success" size="mini" @click="submitForm">保存</el-button>
            </el-col>
          </el-row>
        </div>

        <div>
          <el-form ref="formProductTempBasic" :model="form" :rules="rulesProductTempBasic" label-width="130px">
            <el-row>
              <el-col :span="6">
                <el-form-item label="产品分类" prop="productCategory">
                  <el-select v-model="form.productCategory" placeholder="请选择产品分类" :style="{width: '100%'}" @change="productCategoryChange" filterable clearable>
                    <el-option
                      v-for="(item, index) in configCategoryOptions"
                      :key="index"
                      :label="item.categoryName"
                      :value="item.categoryCode"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="产品来源" prop="productSourceType">
                  <el-select v-model="form.productSourceType" placeholder="请选择产品来源" :style="{width: '100%'}">
                    <el-option
                      v-for="(item, index) in productSourceTypeOptions"
                      :key="index"
                      :label="item.dictLabel"
                      :value="item.dictValue"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="价格系数" prop="standardPriceCoefficient">
                  <el-input v-model="form.standardPriceCoefficient" placeholder="价格系数*采购价格=售价(¥)" clearable :style="{width: '100%'}"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="采购价格" prop="buyingPrice">
                  <el-input v-model="form.buyingPrice" placeholder="请输入采购价格" clearable :style="{width: '100%'}"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="产品共享" prop="productSharingType">
                  <el-select v-model="form.productSharingType" @change="productSharingTypeChange"  placeholder="请选择产品共享" :style="{width: '100%'}">
                    <el-option
                      v-for="(item, index) in productSharingTypeOptions"
                      :key="index"
                      :label="item.dictLabel"
                      :value="item.dictValue"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="是否佣金" prop="isCommissionType">
                  <el-select v-model="form.isCommissionType" @change="isCommissionTypeChange" :disabled="isCommissionTypeDisabled" placeholder="请选择是否佣金" :style="{width: '100%'}">
                    <el-option
                      v-for="(item, index) in isCommissionTypeOptions"
                      :key="index"
                      :label="item.dictLabel"
                      :value="item.dictValue"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="佣金率（%）" prop="commissionRate">
                  <el-input v-model="form.commissionRate" :disabled="commissionRateDisabled" placeholder="请输入佣金率" clearable :style="{width: '100%'}"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="采购链接" prop="buyingLink">
                  <el-input v-model="form.buyingLink" placeholder="请输入采购链接" clearable :style="{width: '100%'}"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="是否暂存" prop="isStaging">
                  <el-select v-model="form.isStaging" placeholder="请选择是否暂存" :style="{width: '100%'}">
                    <el-option
                      v-for="(item, index) in isStagingOptions"
                      :key="index"
                      :label="item.dictLabel"
                      :value="item.dictValue"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="长度（cm）" prop="length">
                  <el-input v-model="form.length" placeholder="请输入长度（cm）" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="宽度（cm）" prop="width">
                  <el-input v-model="form.width" placeholder="请输入宽度（cm）" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="高度（cm）" prop="height">
                  <el-input v-model="form.height" placeholder="请输入高度（cm）" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="重量（kg）" prop="weight">
                  <el-input v-model="form.weight" placeholder="请输入重量（kg）" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="材料" prop="material">
                  <el-input v-model="form.material" placeholder="请输入材料" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="产品特殊性质" prop="specialType">
                  <!--动态维护报错，后期可排除解决-->
                  <el-checkbox-group v-model="specialTypeArray" prop="specialType">
                    <el-checkbox v-for="(item, index) in specialTypeOptions" :label="item.dictValue" >{{item.dictLabel}}</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" clearable
                            :style="{width: '100%'}"/>
                </el-form-item>
              </el-col>
            </el-row>

            <hr>
          <!--产品自身属性-->
          </el-form>

          <el-form ref="formProductTempAttr" :model="formAttr" label-width="130px">
            <el-row>

              <el-col :span="6" v-for="(caa_item, caa_index) in configAttrAtchList">
                <el-form-item :label="caa_item.attrNameCn" >

                  <el-select v-if="caa_item.attrType==='select'" v-model="formAttr['attr'+caa_index]" :placeholder="caa_item.attrNameEn" clearable :style="{width: '100%'}" @change="$forceUpdate()">
                    <el-option
                      v-for="(item, index) in JSON.parse(caa_item.attrTypeSelect)"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>

                  <el-input v-else  v-model="formAttr['attr'+caa_index]" :placeholder="caa_item.attrNameEn" clearable :style="{width: '100%'}"/>

                </el-form-item>
              </el-col>

            </el-row>
          </el-form>

        </div>
      </el-main>

    </el-container>

  </div>
</template>

<script>

  import {
    //getListProductInitByMain,
    updateProductTempBasic,
    addProductTempBasic,
    getProductTempBasic,
    getListByProductCode,
    getConfigAttrAtchByProductCategory
  } from "@/api/amz/productTempBasic";
  import { getConfigCategoryByDept } from "@/api/amz/configCategory";

  export default {
    name: "ProductTempBasic",
    components: {},
    data() {
      return {
        // 是否显示弹出层
        open: false,
        //选择常用属性弹出层表格
        //productInitVisibleDialog: false,
        // 总条数
        total: 0,
        // 初始化商品表格数据
        ProductInitList: [],
        // 遮罩层
        loading: true,
        //选择常用属性弹出层表格分页
        queryParams: {
          pageNum: 1,
          pageSize: 10
        },

        //基本信息表单
        form: {
          isCommissionType: null,
          commissionRate: null,
          isStaging: 'false',
          specialType: [],
        },
        specialTypeArray: [],//产品特殊性质：属于数组对象，在数据库中也是直接存储为json字符串

        //附加属性表单
        formAttr: {},

        // 产品类别列表-部门
        configCategoryOptions: [],
        // 产品来源字典
        productSourceTypeOptions: [],
        // 产品共享字典
        productSharingTypeOptions: [],
        //是否佣金字典
        isCommissionTypeOptions: [],
        //是否暂存
        isStagingOptions: [],
        // 产品特殊性质字典
        specialTypeOptions: [],
        //产品附加属性表格数据
        productTempAtchList: [],
        //附加属性配置信息
        configAttrAtchList : [],
        //是否佣金禁用
        isCommissionTypeDisabled : false,
        //佣金率禁用
        commissionRateDisabled : false,

        // 表单校验
        rulesProductTempBasic: {
          productSourceType: [
            {required: true, message: "产品来源不能为空", trigger: "change"}
          ],
          buyingPrice: [
            {required: true, message: "采购价格不能为空", trigger: "change"}
          ],
          standardPriceCoefficient: [
            {required: true, message: "价格系数不能为空", trigger: "change"}
          ],
          productSharingType: [
            {required: true, message: "产品共享不能为空", trigger: "change"}
          ],
          productCategory: [
            {required: true, message: "产品分类不能为空", trigger: "change"}
          ],
          isVariation: [
            {required: true, message: "有无变体不能为空", trigger: "change"}
          ],
          specialType: [
            {required: true, message: "产品特殊性质不能为空", trigger: "change"}
          ],
          isStaging: [
            {required: true, message: "是否暂存不能为空", trigger: "change"}
          ],

        }

      };
    },
    created() {
      /* 获取类目配置-部门*/
      this.getConfigCategoryByDept();
      //初始化多级字典
      this.initDicts();
    },
    methods: {
      /* 获取类目配置-部门*/
      getConfigCategoryByDept(){
        getConfigCategoryByDept().then(response => {
          this.configCategoryOptions = response.data;
        });
      },
      //初始化多级字典
      initDicts(){
        this.getDicts("qc_product_source_type").then(response => {
          this.productSourceTypeOptions = response.data;
        });
        this.getDicts("qc_sharing_type").then(response => {
          this.productSharingTypeOptions = response.data;
        });
        this.getDicts("qc_is_commission_type").then(response => {
          this.isCommissionTypeOptions = response.data;
        });
        this.getDicts("qc_special_type").then(response => {
          this.specialTypeOptions = response.data;
        });
        this.getDicts("qc_is_boolean").then(response => {
          this.isStagingOptions = response.data;
        });
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          productCode: null,
          batchNo: null,
          productCategory: null,
          standardPriceCoefficient: null,
          productSourceType: null,
          buyingLink: null,
          buyingPrice: null,
          productSharingType: null,
          isCommissionType: null,
          commissionRate: null,
          productStatus: null,
          specialType: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null
        };
        this.specialTypeArray = [];//产品特殊性质

        this.formAttr = {
          productCode: null,
          attr0: null,
          attr1: null,
          attr2: null,
          attr3: null,
          attr4: null,
          attr5: null,
          attr6: null,
          attr7: null,
          attr8: null,
          attr9: null,
          attr10: null,
          attr11: null,
          attr12: null,
          attr13: null,
          attr14: null,
          attr15: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null
        };
        this.resetForm("form");
        this.resetForm("formAttr");
      },

      // 产品来源字典翻译
      productSourceTypeFormat(row, column) {
        return this.selectDictLabel(this.productSourceTypeOptions, row.productSourceType);
      },
      // 产品共享字典翻译
      productSharingTypeFormat(row, column) {
        return this.selectDictLabel(this.productSharingTypeOptions, row.productSharingType);
      },
      // 是否佣金字典翻译
      isCommissionTypeFormat(row, column) {
        return this.selectDictLabel(this.isCommissionTypeOptions, row.isCommissionType);
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },

      submitForm() {
        if (this.specialTypeArray.length!=0){
          this.form.specialType= JSON.stringify(this.specialTypeArray);
        }
        //提交
        this.$refs["formProductTempBasic"].validate(valid => {
          if (valid) {
            var formData ={
              productTempBasic:this.form,
              productTempAttr:this.formAttr
            };

            if (this.$parent.$parent.$parent.$parent.productCode != null) {
              //修改产品
              updateProductTempBasic(formData).then(response => {
                this.msgSuccess("修改成功");
              });
            } else {
              //新增产品
              addProductTempBasic(formData).then(response => {
                this.form = response.productTempBasic;
                //新增后，将productCode传递给父组件，供其他子组件共同调用
                this.$emit('setProductCode',this.form);
                this.msgSuccess("新增成功");
              });
            }

          }
        });

      },
      /**
       * 通过产品代码获取产品信息
       * 当前方法由父页面main点击修改按钮时调用
       * @param productCode
       */
      getListByProductCode(productCode){
        this.loading = true;
        this.productCode = productCode;
        getListByProductCode(productCode).then(response => {
          this.form = response.data.productTempBasic;
          if (this.form.specialType){//必须判断非空，否则前端控制台报错
            this.specialTypeArray = JSON.parse(this.form.specialType);
          }
          this.formAttr = response.data.productTempAttr;
          this.configAttrAtchList = response.data.configAttrAtchList;

          this.loading = false;
        });
      },

      /**
       * 产品分类变更-动态切换附加属性
       */
      productCategoryChange(){
        //通过产品分类获取附加属性配置信息
        if (this.form.productCategory){
          getConfigAttrAtchByProductCategory(this.form.productCategory).then(response => {
            this.configAttrAtchList = response.data;
          });
        }
      },

      /**
       * 产品共享改变事件
       */
      productSharingTypeChange(){
        if(this.form.productSharingType === "1"){
          //不共享
          //是否佣金禁用
          this.isCommissionTypeDisabled = true;
            //佣金率禁用
          this.commissionRateDisabled = true;
          this.form.isCommissionType = "";
          this.form.commissionRate = "";
        }else{
          //是否佣金禁用
          this.isCommissionTypeDisabled = false;
          //佣金率禁用
          this.commissionRateDisabled = false;
        }
      },

      /**
       * 是否佣金变更事件
       */
      isCommissionTypeChange(){
        if (this.form.isCommissionType==="1"){
          this.form.commissionRate = null ;
          this.commissionRateDisabled = true ;
        }else{
          this.commissionRateDisabled = false ;
        }
      }


    }
  };
</script>
